<?php
namespace App\Libs;

use Config\Sys;
use \GatewayWorker\Lib\Gateway;
use \GatewayWorker\Lib\Db;
use \GatewayWorker\Lib\DbConnection;
use \Workerman\Lib\Timer;

class Users{

    protected $User;

    public function __construct()
    {
        $this->User = \jsonRpcClient::instance('User');
    }

	public function userMessage($client_id, $paras){

        //组装预备要访问的函数(过程)名
        $func = 'cmd_'.$paras['cmd'];
        $result['cmd'] = $paras['cmd'];
        if (method_exists($this, $func))
        {
            $this->$func($client_id, $paras);
        }else{
            Gateway::sendToCurrentClient(json_encode(array(
                'state' => 404,
                'msgid' => 301, //指令参数不正确
            )));
            //Gateway::closeClient($client_id);
        }
    }


    # region 心跳响应
    public function cmd_pong($client_id, $paras)
    {
        //没有指定来源将直接返回心跳数据
        Gateway::joinGroup($client_id, 'public');
        Gateway::sendToCurrentClient(json_encode(array(
            'cmd' => 'pong',
        )));
    }
    # endregion

    # region 传红包给指定玩家
    public function cmd_sendtousercoin($client_id, $paras)
    {
        $data = $this->User->sendToUserCoin($paras);
        $result = $data['data'];
        //print_r($result);
        if($result['state']==200){
            //print_r(Gateway::isUidOnline($result['receiveruno']));
            //print_r(Gateway::getClientIdByUid($result['receiveruno']));
            Gateway::sendToUid('P'.$result['receiveruno'], json_encode($result['receiver']));
            Gateway::sendToCurrentClient(json_encode($result['sender']));
            //Gateway::sendtouid($result['senderuno'], json_encode($result['sender']));
        }else{
            Gateway::sendToCurrentClient(json_encode($result));
        }
        return Gateway::closeCurrentClient();
    }
    # endregion

	# region 用户注册
    public function cmd_register($client_id, $paras){
        $data = $this->User->registerUser($paras);
        //print_r($data);
        $result = $data['data'];
        if($result['state']==200){
            $_SESSION['uid'] = $result['users']['uid'];
            $_SESSION['uno'] = $result['users']['uno'];
            $_SESSION['usertype'] = $result['users']['usertype'];
            $_SESSION['nickname'] = $result['users']['nickname'];
            $_SESSION['token'] = $result['users']['token'];
            //Gateway::bindUid($client_id, $result['users']['uno']);
            //Gateway::bindUid($client_id, $result['users']['uid']);
            Gateway::sendToCurrentClient(json_encode($result));
            if(isset($result['pushusergive']) && is_array($result['pushusergive'])){
                //print_r($result['pushusergive']);
                $parentuno = $result['pushusergive']['uno'];
                unset($result['pushusergive']['uno']);
                Gateway::sendToUid('P'.$parentuno,json_encode($result['pushusergive']));
            }
        }else{
            Gateway::sendToCurrentClient(json_encode($result));
        }
        return Gateway::closeClient($client_id);
    }
    # endregion

    #region用户登录
    public function cmd_userlogin($client_id, $paras){
        $data = $this->User->userLogin($paras);
        $result = $data['data'];
        //print_r($result);
        if($data['state']==200){
            if($result['state']==200) {
                $_SESSION['uid'] = $result['users']['uid'];
                $_SESSION['uno'] = $result['users']['uno'];
                $_SESSION['usertype'] = $result['users']['usertype'];
                $_SESSION['nickname'] = $result['users']['nickname'];
                $_SESSION['token'] = $result['users']['token'];
                //Gateway::bindUid($client_id, $result['users']['uno']);
                //Gateway::bindUid($client_id, $result['users']['uid']);
            }
            Gateway::sendToCurrentClient(json_encode($result));
        }else{
            Gateway::sendToCurrentClient(json_encode($result));
        }
        return Gateway::closeClient($client_id);
    }
    #endregion

    #region检测登录
    public function cmd_checklogin($client_id, $paras)
    {
        $data = $this->User->checkUserLoged($paras);
        $result = $data['data'];
        //print_r($data);
        if($result['state']==200){
            $_SESSION['uid'] = $result['uid'];
            $_SESSION['uno'] = $result['uno'];
            $_SESSION['usertype'] = $result['usertype'];
            $_SESSION['nickname'] = $result['nickname'];
            $_SESSION['token'] = $result['token'];
            //Gateway::bindUid($client_id, $result['uno']);
            //Gateway::bindUid($client_id, $result['uid']);
        }
        //$result['online'] = Gateway::getClientCountByGroup('public');
        $isClose = (isset($result['isclose']) ? $result['isclose'] : 'true');
        unset($result['isclose']);
        unset($result['uno']);
        Gateway::sendToCurrentClient(json_encode($result));
        if($isClose=='true') {
            Gateway::closeClient($client_id);
        }
        return;
    }
    //传送头像
    public function cmd_updateheader($client_id, $paras)
    {
        $userToken = $this->utility->exitsToKen($client_id, $paras);
        $result = array('state'=>404,'cmd'=>$paras['cmd']);
        if($userToken['state']==200){
            $base64_image_content = $paras['base64header'];
            //匹配出图片的格式
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $res)){
                $type = $res[2];
                $file_dir = date('Ymd',time());
                $new_file = __DIR__ . "/../Web/avatar/".$file_dir."/";
                if(!file_exists($new_file))
                {
                    //检查是否有该文件夹，如果没有就创建，并给予最高权限
                    mkdir($new_file, 0700);
                }
                $new_file = $new_file.$userToken['uno'].'.'.$type;
                if (file_put_contents($new_file, base64_decode(str_replace($res[1], '', $base64_image_content)))){
                    $avatar = "avatar/".$file_dir."/".$userToken['uno'].'.'.$type;
                    $result = array(
                        'state'=>200,
                        'cmd'=>$paras['cmd'],
                        'headurl' => $avatar,
                    );
                    # 保存到数据库
                    $this->db->query("UPDATE `rp_users` SET `avatar`='".$avatar."' WHERE `uid`=".$userToken['uid']." LIMIT 1");
                }else{
                    $result = array(
                        'state'=>404,
                        'cmd'=>$paras['cmd'],
                        'msgid'=>10042,//文件上传失败
                    );
                }
            }

        }else{
        	$result['state'] = $userToken['state'];
        	$result['msgid'] = $userToken['msgid'];
        }
        Gateway::sendToCurrentClient(json_encode($result));
        # 是否关闭当前链接
        Gateway::closeClient($client_id);
    }
    //更新昵称
    public function cmd_updatenickname($client_id, $paras)
    {
        $data = $this->User->updateUserNickname($paras);
        $result = $data['data'];
        Gateway::sendToCurrentClient(json_encode($result));
        Gateway::closeClient($client_id);
        return;
    }

    # endregion

    #region 取用户信息
    public function cmd_getuserinfo($client_id, $paras)
    {
        $data = $this->User->getUserInfoForToken($paras);
        $result = $data['data'];
        if($data['state']==200 ){
            if($result['state']==200) {
                $_SESSION['uid'] = $result['users']['uid'];
                $_SESSION['uno'] = $result['users']['uno'];
                $_SESSION['usertype'] = $result['users']['usertype'];
                $_SESSION['nickname'] = $result['users']['nickname'];
                $_SESSION['token'] = $result['users']['token'];
                if(isset($paras['isclose']) && $paras['isclose']=='false')
                {
                    # 在【我的】，请求不要求关闭的资料索取 对应的 Uid UNO 前面加 P 方便后期推送
                    # 其它地方的 UNO 不变
                    Gateway::bindUid($client_id, 'P'.$result['users']['uno']);
                }
                //Gateway::bindUid($client_id, $result['users']['uid']);
                //print_r(Gateway::isUidOnline($result['users']['uno']));
                //print_r(Gateway::getClientIdByUid($result['users']['uno']));
            }
        }
        Gateway::joinGroup($client_id, 'public');
        if(isset($result['marquee'])){
            Gateway::sendToCurrentClient(json_encode($result['marquee']));
            unset($result['marquee']);
        }
        //$result['online'] = Gateway::getClientCountByGroup('public');
        Gateway::sendToCurrentClient(json_encode($result));
    }
    #endregion

    #region 取用户的当前余额
    //public function cmd_getuserfreecoin($client_id, $paras){
    public function cmd_gufc($client_id, $paras){
        global $utility;
        $data = $this->User->getUserCoin($paras);
        //print_r($data);
        $result = $data['data'];
        if(isset($result['online'])) {
            $public_online = Gateway::getClientCountByGroup('public');
            $result['online'] = (intval($result['online']) + intval($public_online));
            $utility->redisSet($utility->redisPrefix['SOSUM'], $result['online']);

            Gateway::sendToCurrentClient(json_encode($result));
            if (!isset($paras['isclose']) && $paras['isclose'] != 'false') {
                Gateway::closeClient($client_id);
            }
        }
    }
    #endregion

    #region 发包记录
    public function cmd_send_red_log($client_id, $paras)
    {
        $data = $this->User->sendRedEnvelopesLog($paras);
        $result = $data['data'];
        Gateway::sendToCurrentClient(json_encode($result));
        Gateway::closeClient($client_id);
    }
    #endregion

    #region 抢包记录
    public function cmd_red_grab_log($client_id, $paras)
    {
        $data = $this->User->grabRedEnvelopesLog($paras);
        $result = $data['data'];
        Gateway::sendToCurrentClient(json_encode($result));
        Gateway::closeClient($client_id);
    }
    #endregion

    #region 取单期红包详情数据
    public function cmd_issue_data($client_id, $paras)
    {
        $data = $this->User->RedEnvelopesForIssueItem($paras);
        $result = $data['data'];
        Gateway::sendToCurrentClient(json_encode($result));
        Gateway::closeClient($client_id);
    }
    #endregion

    #region 转帐记录（传红包日志）
    public function cmd_transfer_log($client_id, $paras)
    {
        $data = $this->User->transferLog($paras);
        $result = $data['data'];
        Gateway::sendToUid('P'.$result['receiveruno'],json_encode($result['receiver']));
        Gateway::sendToCurrentClient(json_encode($result));
        Gateway::closeClient($client_id);
    }
    #endregion

    #region 帐变明细
    public function cmd_coin_log($client_id, $paras)
    {
        $data = $this->User->userCoinLog($paras);
        $result = $data['data'];
        Gateway::sendToCurrentClient(json_encode($result));
        Gateway::closeClient($client_id);
    }
    # endregion

    #region 签到
    public function cmd_signline($client_id, $paras)
    {
        $data = $this->User->signGiveScore($paras);
        $result = $data['data'];
        if($result['state']==200){
            return Gateway::sendToCurrentClient(json_encode($result));
        }else{
            return Gateway::sendToCurrentClient(json_encode($result));
        }
    }
    #endregion

    # region 拉取跑马灯内容
    public function cmd_marquee($client_id, $paras)
    {
        $data = $this->User->getMarquee($paras);
        if($data['state']==200) {
            $result = $data['data'];
            if(empty($result['gameid'])) {
                Gateway::sendToGroup('public', json_encode($result));
            }else{
                Gateway::sendToGroup('game_'.$paras['gameid'], json_encode($result));
            }
        }else{
            Gateway::sendToCurrentClient(json_encode($data));
        }
    }
    # endregion

}